const Router = require('koa-router');
const TeacherRouter = new Router();
const TeacherService = require('../service/TeacherService');
const R = require('../utils/R');
const { isHave } = require('../utils/validators');
const Validators = require('../utils/validators');

TeacherRouter.prefix('/api/v1/teacher');

/**
 * pageNum  页数
 * pageSize  一页的数据量
 */
TeacherRouter.get('/list',async (ctx, next) => {
    let { pageSize, pageNum } = ctx.request.query
    Validators.isNull(pageNum, 'pageNum').isNull(pageSize, 'pageSize')
    let data = await TeacherService.findAll(pageSize, pageNum);
    data.pageSize = pageSize;
        data.pageNum = pageNum;
        ctx.body = R.okData(data)
})

/**
 * user_id 教师ID
 */
TeacherRouter.get('/info', async (ctx, next) => {
    let {userId} = ctx.request.query;
    Validators.isNull(userId, 'userId')
    let data = await TeacherService.findAttrById(userId);
    ctx.body = R.okData(data);
})

TeacherRouter.post('/register', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.username, 'username').isNull(user.password, 'password').isNull(user.nickname, 'nickname')
    .isNull(user.sex, 'sex').isHave(user.sex, [1, 2], 'sex').isNull(user.teacherId, 'teacherId').isNull(user.identity, 'identity')
    .isHave(user.identity, [0, 1, 2], 'identity');
    await TeacherService.saveTeacher(user);
    ctx.body = R.okMsg('注册用户成功');
})

TeacherRouter.post('/delete', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.userId, 'userId')
    await TeacherService.deleteTeacher(user.userId);
    ctx.body = R.okMsg('删除成功')
})

TeacherRouter.post('/login', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.username, 'username').isNull(user.password, 'password')
    let data = await TeacherService.login(user);

    if(data == 210) ctx.body = R.error(data, '用户不存在')
    else if(data == 211) ctx.body = R.error(data, '密码错误')
    else ctx.body = R.okData(data)
})

TeacherRouter.post('/update', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.nickname, 'nickname').isNull(user.identity, 'identity')
    .isNull(user.sex, 'sex').isHave(user.sex, ['1', '2'], 'sex').isNull(user.teacherId, 'teacherId')
    .isHave(user.identity, ['0', '1', '2'], 'identity').isNull(user.userId, 'userId');
    await TeacherService.updateTeacher(user);
    ctx.body = R.okMsg('修改成功')
})

TeacherRouter.post('/password', async (ctx, next) => {
    let user = ctx.request.body;
    Validators.isNull(user.newPassword, 'newPassword').isNull(user.userId, 'userId').isNull(user.oldPassword, 'oldPassword');
    let data = await TeacherService.updatePassword(user);
    if(data.name || data[0] == 0){
        ctx.body = R.errorMsg(data.name || '修改密码失败')
    }else {
        ctx.body = R.okMsg('修改密码成功')
    }
})

module.exports = TeacherRouter